﻿using AntdUI;
using WenAntdUI.Interfaces;

namespace WenAntdUI.Controls;

[ToolboxItem(true)]
public class DictSelect : IControl, IEditControl
{
    private string category;
    private readonly IFreeSql fsql;
    private readonly Select select;
    public DictSelect() : base()
    {
        this.Size = new Size(100, 35);
        //获取数据库
        fsql = App.GetService<IFreeSql>();

        select = new Select
        {
            Dock = DockStyle.Fill
        };
        Controls.Add(select);

        select.SelectedValueChanged += Select_SelectedValueChanged;
    }

    public DictSelect(string category) : this()
    {
        Category = category;
    }

    private void Select_SelectedValueChanged(object sender, ObjectNEventArgs e)
    {
        Text = (e.Value as SelectItem)?.Code;

        this.Value = Text;
        ValueChanged?.Invoke(this, Text);
    }
    //[Category("功能"), Description("字典内容")]
    //public new string Text
    //{
    //    get => select.Text;
    //    set
    //    {
    //        if (value != select.Text)
    //        {
    //            select.Text = value;
    //            OnPropertyChanged(nameof(Text));
    //        }
    //    }
    //}


    public string _value;
    public object Value { get => (select.SelectedValue as SelectItem)?.Code; set => SetValue(value); }

    [Description("字典标签名称")]
    [Category("功能")]
    /// <summary>
    /// 字典标签
    /// </summary>
    public string Category { get => category; set { category = value; SetItems(); } }

    public event EventHandler<object> ValueChanged;

    private void SetItems()
    {
        var items = fsql?.Select<SysDict>()
            .Where(t => t.Category == category)
            .ToList(a => new SelectItem(a.Name, a.Code));
        if (items.Count > 0)
        {
            select.Items.AddRange([.. items]);
        }
    }

    public void SetValue(object value)
    {
        if (value == null || value is DBNull) return;
        var dict = select.Items.ToList<SelectItem>().FirstOrDefault(a => a.Code == (string)value);
        if (dict != null)
        {
            select.SelectedValue = dict;
            if (this._value != dict.Code)
            {
                this._value = dict.Code;
                OnPropertyChanged(nameof(Value));
            }
        }
    }

    public class SelectItem(string name, string code)
    {
        public string Name { get; set; } = name;
        public string Code { get; set; } = code;
        public override string ToString()
        {
            return Name;
        }
    }
}
